/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ee.locationsearch.rss;

import ee.moviesearch.rss.Feed;
import ee.moviesearch.rss.FeedMessage;
import ee.moviesearch.rss.RSSFeedParser;
import ee.ut.math.esi.service.LocationFinder;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Set;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.ejb.Stateless;

/**
 *
 * @author Yuuzaa
 */
@WebService(serviceName = "LocationSearchService")
@Stateless()
public class LocationSearchService {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "findLocations")
    public Set<String> findLocations(@WebParam(name = "title") String title) throws UnsupportedEncodingException {
        title = URLEncoder.encode(title,"UTF-8");
        RSSFeedParser parser = new RSSFeedParser(
                "http://www.imsdb.com/feeds/fromtitle.php?title=" + title + "%");
        Feed feed = parser.readFeed();
        String url = "";
        if (feed.getMessages() != null) {
            for (FeedMessage message : feed.getMessages()) {
                url = message.toString();
                break;
            }
        }
        URL urlInput;
        try {
            urlInput = new URL(url);
            LocationFinder loc = new LocationFinder();
            Set<String> list = loc.getLocationsFromURL(urlInput);
            return list;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
